<template>
  <div class="box">
    <!-- 顶部导航栏 -->
    <div class="header-container">
        <span v-if="status === 1"
              class="businessBtn">营业中</span>
      <span v-else
            class="businessBtn closing">打烊中</span>
      <div :key="restKey"
           class="right-menu">
        <div class="avatar-wrapper">
          <!--    菜单栏      -->
          <el-dropdown>
            <!--     头像       -->
            <div class="avatar-container">
              <el-avatar :size="50" fit="cover" class="custom-avatar"
                         v-if="avatar" :src="avatar"/>
              <el-avatar :size="50" fit="cover" class="custom-avatar"
                         v-else icon="el-icon-user-solid"/>
            </div>
            <el-dropdown-menu slot="dropdown" class="el-dropdown-menu">
              <el-dropdown-item @click.native="userInfo()">
                <i class="iconfont icon-icon-test35"/>
                个人信息
              </el-dropdown-item>
              <el-dropdown-item @click.native="addressInfo()">
                <i class="iconfont icon-icon-test20"/>
                地址信息
              </el-dropdown-item>
              <el-dropdown-item @click.native="updatePwd()">
                <i class="iconfont icon-mima"/>
                修改密码
              </el-dropdown-item>
              <el-dropdown-item @click.native="logout()">
                <i class="iconfont icon-tuichu"/>
                退出登录
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>

        <div class="avatar-wrapper">
          <router-link to="/shoppingCart">
            <span class="el-dropdown-link" style="color: black;margin-top: 10px;font-size: 20px">
            <i class="iconfont icon-icon-test11" style="font-size: 24px"/>
              购物车
            </span>
          </router-link>
        </div>

        <div class="avatar-wrapper">
          <router-link to="/orders">
            <span class="el-dropdown-link" style="color: white;margin-top: 10px;font-size: 20px">
              <el-badge :value="pendingPayment" class="item">
                <i class="el-icon-s-order" style="font-size: 24px;"/>
              </el-badge>
              我的订单
            </span>
          </router-link>
        </div>
      </div>
    </div>

    <!-- 个人资料弹层 -->
    <UserInfo ref="userInfoDialog" :avatar="avatar" @imageAvatarSuccess="uploadImage"/>

    <!-- 地址簿弹层 -->
    <AddressInfo ref="addressInfoDialog" @save="addressInfo"/>

    <!--  修改密码弹层  -->
    <EditPwd ref="editPwdDialog"/>

    <el-container class="heightAll">
      <!--   侧边栏   -->
      <div class="aside">
        <el-aside class="el-aside">
          <div class="logo">
            <div class="sidebar-logo">
              <img src="@/assets/jindowin_w.png" style="width: 200px;height: 50px;margin-right: 100px;margin-top: 10px">
            </div>
          </div>
          <el-menu
              default-active="10"
              class="el-menu-vertical-demo"
              background-color="#545c64"
              text-color="#fff"
              active-text-color="#FFC200">
            <el-menu-item
                v-for="item in menuItems"
                :key="item.id"
                :index="item.id"> <!--使用 id 作为 index-->
              <span style="font-size: 18px;margin-right: 100px;">{{ item.name }}</span> <!-- 显示 name 字段 -->
            </el-menu-item>
          </el-menu>

        </el-aside>
      </div>

      <!--   表格   -->
      <el-main>
        <div class="dashboard-container">
          <div class="container">
            <div class="tableBar">
              <el-page-header style="float: left" @back="goBack" content="首页"/>
              <label style="margin-right: 20px;font-size: 40px">我的购物车</label>
              <el-button style="float: right" type="danger" @click="handleDelete('批量删除',null)">批量删除</el-button>
            </div>
          </div>
          <el-table v-if="tableData.length > 0"
                    ref="multipleTable"
                    :data="tableData"
                    stripe
                    @selection-change="handleSelectionChange"
                    :summary-method="getSummaries"
                    show-summary
                    class="tableBox">
            <el-table-column type="selection" width="45"/>
            <el-table-column prop="name"
                             label="菜品名称"/>
            <el-table-column prop="image"
                             label="图片">
              <template slot-scope="{ row }">
                <el-image style="width: 40px; height: 40px; border: none; cursor: pointer"
                          :src="row.image">
                  <div slot="error"
                       class="image-slot">
                    <img src="./../../assets/noImg.png"
                         style="width: auto; height: 40px; border: none">
                  </div>
                </el-image>
              </template>
            </el-table-column>
            <el-table-column label="口味">
              <template slot-scope="scope">
                <span style="margin-right: 10px">{{ scope.row.dishFlavor }}</span>
              </template>
            </el-table-column>
            <el-table-column label="售价">
              <template slot-scope="scope">
                <span style="margin-right: 10px">￥{{ (scope.row.amount).toFixed(2) * 100 / 100 }}</span>
              </template>
            </el-table-column>
            <el-table-column label="数量" width="205">
              <template slot-scope="scope">
                <el-input-number
                    v-model="scope.row.number" @change="handleChange(scope.row)"
                    :min="0">
                </el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="金额" prop="totalPrice">
              <template slot-scope="scope">
                <span style="margin-right: 10px">￥{{
                    (scope.row.amount * scope.row.number).toFixed(2) * 100 / 100
                  }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作"
                             width="250"
                             align="center">
              <template slot-scope="scope">
                <el-button type="text"
                           class="redBug"
                           @click="handleDelete('单删',scope.row.id)">
                  <i class="iconfont icon-shanchu"/>
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <Empty v-else
                 :is-search="isSearch"/>
          <el-pagination
              class="pageList"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="page"
              :page-sizes="[10, 20, 30, 40, 50]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
          </el-pagination>

        </div>
      </el-main>

    </el-container>
  </div>

</template>


<script lang="ts">
import {Component, Vue, Watch} from 'vue-property-decorator';
import EditPwd from "@/components/EditPwd/index.vue";
import UserInfo from "@/components/UserInfo/index.vue";
import {getList} from "@/api/category";
import axios from "axios";
import UploadImage from "@/components/ImgUpload/index.vue";
import {addShoppingCart, deleteBatchShoppingCart, deleteShoppingCart, getShoppingCartList} from '@/api/shoppingcart';
import {getUserInfo} from "@/api/user";
import AddressInfo from "@/components/AddressInfo/index.vue";
import {alipay, insertOrders, ordersCount} from "@/api/order";
import Empty from "@/components/Empty/index.vue";


@Component({
  components: {Empty, AddressInfo, UploadImage, UserInfo, EditPwd}
})
export default class dishView extends Vue {
  private page = 1
  private pageSize = 10
  private total = 0
  private tableData: any[] = []
  private menuItems = []
  private restKey = 0
  private setStatus = 1
  private status = 1
  private checkList: any[] = []
  private id: any
  private selNum = 0
  private number = 1
  private totalPrice = 0 as any
  private selected = 0;
  private avatar = ''
  private pendingPayment = 0

  private uploadImage(newImage: string) {
    this.avatar = newImage;
  }

  created() {
    this.getStatus();
    this.getUserAvatar();
    this.getOrders_1Count();
    this.fetchMenuItems();
    this.getShoppingCart();
  }

  @Watch('tableData')
  onTableDataChanged() {
    this.$nextTick(() => {
      const footerCell = (this.$refs.multipleTable as any).$refs.footerWrapper
          ?.querySelector(".el-table__footer")
          ?.querySelectorAll("td")[7]
          ?.querySelector(".cell");

      if (footerCell) {
        footerCell.innerHTML = `
          <button
            type="button"
            class="el-button el-button--default el-button--mini cart-btn"
            style="color: #fff; background: #FFC200;width:120px;height:50px;font-size:20px">
            <span>结算</span>
          </button>`;

        footerCell.onclick = () => {
          console.log("点击", this.totalPrice);
          this.orderPay();
        };
      }
    });
  }

  addressInfo() {
    (this.$refs.addressInfoDialog as any).dialogAddressVisible = true;

  }

  async orderPay() {
    if (this.checkList.length === 0) {
      return this.$message.error('请选择购买对象')
    }

    let addressBookId = localStorage.getItem('addressId');
    if (addressBookId == null) {
      await this.addressInfo();
      addressBookId = localStorage.getItem('addressId');
    }
    sessionStorage.setItem("totalPrice",this.totalPrice);
    const data = {
      addressBookId: addressBookId,
      amount: this.totalPrice,
      payMethod: 1,
      ids: this.checkList,
    }
    insertOrders(data).then((res) => {
      if (res.data.code === 1) {
        const params = {
          subject: res.data.data.consignee,
          traceNo: res.data.data.orderNumber,
          totalAmount: res.data.data.orderAmount
        }
        alipay(params).then(res => {
          if (res.data.code === 1) {
            console.log(res.data.data);
            document.write(res.data.data);
            this.$nextTick(() => {
              // 提交支付表单
              const alipayWap = this.$refs.alipayWap as HTMLElement;
              const form = alipayWap.children[0] as HTMLFormElement;
              if (form) {
                form.submit();
              }
              setTimeout(() => {
                // this.toPayFlag = false;
              }, 500);
            })
          }
        })
      } else {
        this.$message.error(res.data.msg)
      }
    })
  }

  getOrders_1Count() {
    ordersCount().then(res => {
      if (res.data.code === 1) {
        this.pendingPayment = res.data.data.pendingPayment;
      }
    })
  }

  getUserAvatar() {
    getUserInfo().then(res => {
      if (res.data.code === 1) {
        this.avatar = res.data.data.avatar;
      }
    })
  }

  handleDelete(type: string, id: any) {
    if (type === '批量删除' && id === null) {
      if (this.checkList.length === 0) {
        return this.$message.error('请选择删除对象')
      }
    }
    this.$confirm('此操作永久删除改数据, 确定吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      deleteBatchShoppingCart(type === '单删' ? id : this.checkList.join(',')).then(res => {
        if (res.data.code === 1) {
          this.$message.success("删除成功");
          this.getShoppingCart();
        } else {
          this.$message.error(res.data.meg);
        }
      }).catch((err) => {
        this.$message.error(err.message);
      })
    })

  }

  handleSelectionChange(val: any) {
    let checkArr: any[] = []
    this.selNum = val.length
    val.forEach((n: any) => {
      checkArr.push(n.id)
    })
    this.checkList = checkArr
    //console.log(this.checkList.join(','));
    for (var i in this.tableData) {
      this.tableData[i].selected = checkArr.includes(this.tableData[i].id) ? 1 : 0;
    }
  }

  getSummaries(param) {
    const {columns, data} = param;
    const sums: any[] = [];
    if (columns.length > 0) {
      this.totalPrice = this.tableData
          .filter((item) => item.selected == 1)
          .map((row) => row.number * row.amount)
          .reduce((total, num) => total + num, 0)
          .toFixed(2);
    } else {
      this.totalPrice = 0;
    }
    columns.forEach((column, index) => {
      if (index === 0) {
        sums[index] = '总价';
        return;
      }
      if (index === 5) {
        sums[index] = '已选中商品' + this.selNum + '个'
        return;
      }
      if (index === 6) {
        sums[index] = '￥' + this.totalPrice + '元'
        return;
      }
    });
    return sums;
  }

  handleChange(goods) {
    const originalNumber = goods.originalNumber; // 获取原始数量
    const currentNumber = goods.number; // 获取修改后的数量

    // 判断数量是增加还是减少
    if (currentNumber > originalNumber) {
      //alert(`增加数量: ${currentNumber - originalNumber}`);
      addShoppingCart(goods);
    } else {
      //alert(`减少数量: ${originalNumber - currentNumber}`);
      deleteShoppingCart(goods).then((res) => {
        if (res.data.code === 1) {
          this.getShoppingCart();
        }
      });
    }

    // 更新原始数量为当前修改后的数量
    goods.originalNumber = currentNumber;
  }

  goBack() {
    this.$router.push({
      path: "/index",
    });
  }

  handleSizeChange(pageSize: number) {
    this.pageSize = pageSize;
    this.getShoppingCart()
  }

  handleCurrentChange(page: number) {
    this.page = page;
    this.getShoppingCart()
  }

  getShoppingCart() {
    const params = {
      page: this.page,
      pageSize: this.pageSize,
    }
    getShoppingCartList(params).then((res) => {
      if (res.data.code === 1) {
        this.tableData = res.data.data.records.map(item => ({
          ...item,
          originalNumber: item.number,
        }))
        this.total = res.data.data.total
      }
    }).catch((err) => {
      this.$message.error(err.message);
    })
  }

  fetchMenuItems() {
    getList().then(res => {
      this.menuItems = res.data.data;
    })
  }

  userInfo() {
    (this.$refs.userInfoDialog as any).dialogVisible = true;
  }

  updatePwd() {
    (this.$refs.editPwdDialog as any).dialogFormVisible = true;  // 调用子组件中的属性
  }

  getStatus() {
    const token = sessionStorage.getItem('authentication')

    axios({
      method: "get",
      url: "/api/user/shop/status",
      headers: {
        authentication: token
      }
    }).then(res => {
      if (res.data.code === 1) {
        this.status = res.data.data
        this.setStatus = this.status
      }
    }).catch(err => {
      this.$message.error(err.message);
    })
  }

  logout() {
    this.$router.push({
      path: '/'
    })
  }
}
</script>


<style lang="scss" scoped>
.custom-avatar {
  display: flex; /* 设为 Flexbox 布局 */
  align-items: center; /* 垂直居中 */
  justify-content: center; /* 水平居中 */
  margin: 0; /* 清除任何外边距 */
  padding: 0; /* 清除任何内边距 */
}

.avatar-container {
  width: 50px;
  height: 50px;
}

a {
  text-decoration: none;
}

.aside {
  width: 200px;
  background-color: #FFC200;
  height: 100vh;
  overflow: hidden;
  overflow-y: auto;
}

.el-aside {
  width: 200px;
  height: 100vh;
  overflow: hidden;
}

.logo {
  background-color: #FFC200; /* 设置背景颜色 */
  z-index: 1000; /* 确保它位于其他内容之上 */
  position: fixed;
}

.heightAll {
  height: 100%;
}

.el-menu-vertical-demo {
  margin-top: 53px;
  padding-top: 20px;
  height: 100%;
}

.redBug {
  color: #ff0000 !important;
  position: relative;
}

.blueBug::after {
  position: absolute;
  right: -6px;
  height: 14px;
  width: 0px;
  border-right: solid 1px #EBEEF5 !important;
}

.dashboard {
  &-container {
    margin: 60px;

    .container {
      background: #fff;
      position: relative;
      z-index: 1;
      padding: 30px 28px;
      border-radius: 4px;

      .tableBar {
        gap: 10px; /* 组件间距，也可以使用 margin */

      }

      .tableBox {
        width: 100%;
        border: 1px solid #F3F4F7;
        border-bottom: 0;
      }

      .pageList {
        text-align: center;
        margin-top: 30px;
      }

      .normal-btn {
        background: #303133;
        color: white;
        margin-left: 20px;
      }
    }
  }
}
</style>
<style scoped>

.el-dropdown-link {
  cursor: pointer;
  font-size: 15px;
  margin-top: -5px;
}

.el-icon-arrow-down {
  font-size: 20px;
  line-height: 50px;
}

.header-container {
  background: #FFC200;
  position: fixed; /* 固定在页面顶部 */
  top: 0; /* 从顶部开始 */
  left: 0; /* 从左侧开始 */
  right: 0; /* 直到右侧 */
  height: 72px; /* 设置导航栏高度，根据需求调整 */
  z-index: 1000;
}

.box {
  position: fixed;
  width: 100%;
  height: 100%;
}

.businessBtn {
  height: 20px;
  line-height: 20px;
  background: #fd3333;
  border: 1px solid #ffffff;
  border-radius: 4px;
  display: inline-block;
  padding: 0 6px;
  margin-top: 25px;
  color: #fff;

  .closing {
    background: #606266;
  }
}

.right-menu {
  float: right;
  margin-right: 20px;
  color: #333333;
  font-size: 14px;

  span {
    width: 130px;
    display: inline-block;
    cursor: pointer;

    &:hover {
      background: rgba(255, 255, 255, 0.52);
    }
  }

  &:focus {
    outline: none;
  }

  .avatar-wrapper {
    margin-top: 14px;
    margin-left: 18px;
    position: relative;
    float: right;
    width: 120px;
    text-align: left;
  }
}


</style>
